package com.oneguy.server;

import com.oneguy.server.log.Log;
import org.apache.commons.io.IOUtils;

import javax.xml.bind.DatatypeConverter;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;

/**
 * Created by ZuoShu on 17/9/14.
 */
public class Server implements TcpConnectionListener {
    private static final String TAG = Server.class.getSimpleName();
    private static String proFileName = "/serverConfig.properties";

    private int localPort;

    public static void main(String[] args) {
        Log.d(TAG, "start to run server");
        Server server = new Server();
        server.start();
    }

    public void start() {
        readProperties();
        startServer();
    }

    private void readProperties() {
        InputStream in = null;
        try {
            Properties properties = new Properties();
            in = ClassLoader.class.getResourceAsStream(proFileName);
            properties.load(in);
            localPort = Integer.parseInt(properties.getProperty("port"));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(in);
        }
    }

    private void startServer() {
        try {
            ServerSocket serverSocket = new ServerSocket(localPort);
            while (true) {
                Log.d(TAG, "listening on port:" + localPort);
                Socket client = serverSocket.accept();
//                Log.d(TAG, "client come in:" + client.getInetAddress());
                TcpConnection tcpConnection = new TcpConnection();
                tcpConnection.setListener(this);
                tcpConnection.connect(client);
            }
        } catch (Exception e) {
            Log.d(TAG, "服务器异常: " + e.getMessage());
        }
    }


    public void onConnect(TcpConnection connection) {
        Log.d(TAG, "onConnect:" + (connection == null ? null : connection.getSocket().getInetAddress()));
    }

    public void onDisconnect(TcpConnection connection) {
        Log.d(TAG, "onDisconnect:" + (connection == null ? null : connection.getSocket().getInetAddress()));
    }

    public void onException(TcpConnection connection, Exception e) {
        Log.d(TAG, "onException:" + e.toString());
    }

    public void onReceive(TcpConnection connection, byte[] data) {
        Log.d(TAG, "onReceive:" + Utils.printHexBinary(data));
    }

    public void onSend(TcpConnection connection, byte[] data) {
        Log.d(TAG, "onSend:" + Utils.printHexBinary(data));
    }
}
